﻿using Common.Extension;

namespace DesignModeConsole.行为型.解释器模式.加减乘除;

public class ExpressionInterpreter1
{
    /// <summary>
    /// 实现一个简单的语法算法
    /// 4 5 6 7 - * +
    /// 实现(4-5)*6+7
    /// </summary>
    public void SampleOperator(string str)
    {
        var list = new List<IExpression1>();

        var strArray = str.Split(" ");
        for (var i = 0; i < (strArray.Length + 1) / 2; i++)
        {
            list.Add(new NumberExpression(strArray[i].ToInt()));
        }

        var startIndex = (strArray.Length + 1) / 2;
        for (var i = startIndex; i < strArray.Length; i++)
        {
            if (strArray[i] is not "+" and not "-" and not "*" and not "/")
            {
                throw new NotSupportedException("不支持的操作符");
            }

            var number1 = list[0];
            var number2 = list[1];

            list.RemoveAt(0);
            list.RemoveAt(0);

            IExpression1 result = new NumberExpression(0);
            switch (strArray[i])
            {
                case "+":
                    result = new AdditionExpression(number1, number2);
                    break;

                case "-":
                    result = new SubtractionExpression(number1, number2);
                    break;

                case "*":
                    result = new MultiplicationExpression(number1, number2);
                    break;

                case "/":
                    result = new DivisionExpression(number1, number2);
                    break;
            }
            list.Insert(0, result);
        }
        if (list.Count != 1)
        {
            throw new ArgumentException("无效的表达式");
        }
        Console.WriteLine($"计算结果是  {list[0].Interpret()}");
    }
}